<!-- 权限管理，核心组件 -->
<template>
  <div class="mb-col" style="height: 100%">
    <!-- 按钮部分 -->
    <el-form @submit.prevent :disabled="isLoadingData" inline>
      <el-form-item>
        <el-button type="success" :loading="isLoadingData" :icon="Plus" @click="handleOpenAddOrEditDialog()">
          新建
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="modelSearchKey"
          clearable
          placeholder="输入内容搜索"
          @keyup.enter="getDataList(true)"
          @clear="getDataList(true)"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="isLoadingData" :icon="Search" @click="getDataList(true)">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="danger"
          :loading="isDeletingData"
          :icon="Delete"
          @click="handleDeleteBatchConfirm(refTable.getSelectionRows())"
          :disabled="refTable && refTable.getSelectionRows().length === 0"
        >
          删除
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 表格部分 -->
    <el-table ref="refTable" :border="true" :data="modelDataList" v-loading="isLoadingData" style="height: 100%">
      <el-table-column type="selection" width="46" align="center" />
      <el-table-column label="权限名称" prop="name" />
      <el-table-column label="权限代码" prop="value" />
      <el-table-column label="业务类型" width="120px" prop="business" />
      <el-table-column label="描述" prop="description" />
      <el-table-column label="创建人" width="120px" prop="createUser" />
      <el-table-column label="创建时间" width="180px" prop="createTime" />
      <el-table-column label="排序码" width="60px" prop="sortCode" />
      <el-table-column width="150px" fixed="right">
        <template #header>
          <div class="custom-row-center">操作</div>
        </template>
        <template #default="{ row }">
          <el-row>
            <el-col :span="12">
              <el-button
                text
                type="primary"
                size="small"
                @click="handleOpenAddOrEditDialog(row?.id)"
                :loading="isDeletingData"
              >
                <el-icon>
                  <Edit />
                </el-icon>
                编辑
              </el-button>
            </el-col>
            <el-col :span="12">
              <el-button text type="danger" size="small" @click="handleDeleteConfirm(row)" :loading="isDeletingData">
                <el-icon>
                  <Delete />
                </el-icon>
                删除
              </el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页部分 -->
    <el-pagination
      layout="-> , prev, pager, next, sizes, jumper, total"
      v-model:current-page="modelPageCurrent"
      v-model:page-size="modelPageSize"
      :disabled="isLoadingData"
      :total="modelPageTotal"
      style="margin-top: 8px"
      background
    />

    <!-- 添加修改权限对话框 -->
    <dialog-add-or-edit-permis-manage ref="refAddOrEditDialog" @save-data-success="getDataList(true)" />
  </div>
</template>
<script setup lang="ts">
  import { onMounted, ref, watch } from 'vue'
  import { SysPermissionApi } from '/@/api/sysApi/SysPermissionApi.ts'
  import { CommonPageParam } from '/src/type/CommonPageParam.ts'
  import { Delete, Edit, Plus, Search } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
  import DialogAddAndEditPermisManage from '/src/views/manage/permission/addAndEdit/DialogAddOrEditPermisManage.vue'
  import DialogAddOrEditPermisManage from '/@/views/manage/permission/addAndEdit/DialogAddOrEditPermisManage.vue'
  import PermissionType = SysPermissionApi.PermissionType

  const refTable = ref<InstanceType<typeof ElTable>>() // 表格
  const refAddOrEditDialog = ref<InstanceType<typeof DialogAddAndEditPermisManage>>() // 添加编辑对话框

  const modelSearchKey = ref<string>() // 搜索关键字
  const modelDataList = ref<PermissionType[]>([]) // 表格数据
  const modelPageCurrent = ref<number>(CommonPageParam.DEFAULT_CURRENT) // 当前页
  const modelPageSize = ref<number>(CommonPageParam.DEFAULT_SIZE) // 每页条数
  const modelPageTotal = ref<number>() // 总记录数量

  const isLoadingData = ref<boolean>(false) // 是否正在加载表格信息
  const isDeletingData = ref<boolean>(false) // 是否正在删除数据

  onMounted(() => {
    getDataList(true)
  })

  /**
   * 改变分页（改变分页的事件将不被element支持，官方推荐使用双向绑定页码并监听其值方式分页）
   */
  watch(modelPageCurrent, () => getDataList())
  watch(modelPageSize, () => getDataList())

  /**
   * 查询表格数据
   * @param isClearPage 是否清除页面从头开始查询
   */
  const getDataList = async (isClearPage = false) => {
    isLoadingData.value = true
    const params = {
      current: modelPageCurrent.value,
      size: modelPageSize.value,
      searchKey: modelSearchKey.value,
    }
    if (isClearPage) {
      params.current = CommonPageParam.DEFAULT_CURRENT
      params.size = CommonPageParam.DEFAULT_SIZE
    }
    try {
      const {
        data: { data },
      } = await SysPermissionApi.page(params)
      modelPageCurrent.value = data.current
      modelPageSize.value = data.size
      modelPageTotal.value = data.total
      modelDataList.value = data.records
      console.log(modelDataList.value)
    } finally {
      isLoadingData.value = false
    }
  }

  /**
   * 批量删除数据
   * @param dataList 删除的数据集合，主要依靠id字段
   */
  const deleteDataBatch = async (dataList: PermissionType[]) => {
    isDeletingData.value = true
    try {
      await SysPermissionApi.deleteBatch(dataList)
      ElMessage.success('删除成功')
      await getDataList(false)
    } finally {
      isDeletingData.value = false
    }
  }

  /**
   * 删除一条数据的确认弹窗
   * @param data 删除的数据，主要依靠id字段
   */
  const handleDeleteConfirm = (data: PermissionType) => {
    if (data?.id) {
      ElMessageBox.confirm(`确定要删除“${data.name}”吗？`, {
        title: '警告！',
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => deleteDataBatch([data]))
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '操作已取消',
          })
        })
    } else {
      console.warn('未正确传递data?.id', data)
    }
  }

  /**
   * 批量删除确认弹窗
   * @param dataList 删除的数据集合，主要依靠id字段
   */
  const handleDeleteBatchConfirm = (dataList: PermissionType[]) => {
    if (dataList) {
      ElMessageBox.confirm(`确定要删除选中的${dataList.length}条数据吗？`, {
        title: '警告！',
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => deleteDataBatch(dataList))
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '操作已取消',
          })
        })
    }
  }

  /**
   * 打开添加或编辑对话框
   * @param id
   */
  const handleOpenAddOrEditDialog = (id?: number) => {
    refAddOrEditDialog.value?.handleOpenDialog(id)
  }
</script>
<style scoped lang="scss"></style>